#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
昆明地铁数据分析与可视化
本脚本基于全国地铁数据，重点分析昆明市地铁的建设情况和客流量变化
此版本仅关注已运营的地铁站点
"""

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.font_manager import FontProperties
import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter
import matplotlib.patches as mpatches
import geopandas as gpd
import warnings
import datetime
import calendar
from pathlib import Path

# 忽略警告
warnings.filterwarnings('ignore')

# 设置中文字体
try:
    font = FontProperties(fname=r"C:\Windows\Fonts\SimHei.ttf")
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
except:
    print("无法加载SimHei字体，使用系统默认字体")

# 创建输出目录
output_dir = "analysis_results/kunming_analysis"
os.makedirs(output_dir, exist_ok=True)

print("开始昆明地铁数据分析...")

def load_data():
    """加载清洗后的地铁数据"""
    data_dir = Path("data/processed/cleaned_data")
    
    # 加载站点数据
    print("加载站点数据...")
    stations_2023_path = data_dir / "cleaned_stations_2023.csv"
    stations_2023_df = pd.read_csv(stations_2023_path)
    
    # 加载线路数据
    print("加载线路数据...")
    lines_2023_path = data_dir / "cleaned_lines_2023.csv"
    lines_2023_df = pd.read_csv(lines_2023_path)
    
    # 加载2024年数据
    stations_2024_path = data_dir / "cleaned_stations_2024.csv"
    if os.path.exists(stations_2024_path):
        stations_2024_df = pd.read_csv(stations_2024_path)
        lines_2024_path = data_dir / "cleaned_lines_2024.csv"
        lines_2024_df = pd.read_csv(lines_2024_path)
    else:
        stations_2024_df = pd.DataFrame()
        lines_2024_df = pd.DataFrame()
    
    # 加载客流量数据
    print("加载客流量数据...")
    flow_path = data_dir / "cleaned_flow_data.csv"
    flow_df = pd.read_csv(flow_path)
    
    print(f"数据加载完成!")
    return stations_2023_df, lines_2023_df, stations_2024_df, lines_2024_df, flow_df

def filter_operating_stations(stations_df):
    """
    筛选出已经投入运营的地铁站点
    
    参数:
    stations_df (DataFrame): 包含站点数据的DataFrame
    
    返回:
    DataFrame: 只包含运营中的站点
    """
    # 检查是否有直接表示运营状态的列
    status_columns = [col for col in stations_df.columns if '状态' in col or 'status' in col.lower()]
    
    if status_columns:
        # 如果有状态列，筛选出运营中的站点
        status_col = status_columns[0]
        operating_keywords = ['运营', '营运', '运行', 'operating', 'in operation']
        
        # 创建筛选条件
        operating_filter = stations_df[status_col].str.contains('|'.join(operating_keywords), case=False, na=False)
        operating_stations = stations_df[operating_filter]
        
        print(f"根据{status_col}列筛选出{len(operating_stations)}个运营中的站点")
        return operating_stations
    
    # 如果没有明确的状态列，我们可以基于其他特征进行推断
    # 例如，假设所有已有经纬度信息且已分配线路的站点都是运营中的
    
    # 检查经纬度列
    coord_columns = []
    for possible_names in [('Lng', 'Lat'), ('longitude', 'latitude'), ('经度', '纬度')]:
        if possible_names[0] in stations_df.columns and possible_names[1] in stations_df.columns:
            coord_columns = list(possible_names)
            break
    
    if not coord_columns:
        # 找不到经纬度列，尝试使用所有可用数据
        print("警告: 无法确定运营状态，使用所有站点数据")
        return stations_df
    
    # 假设有经纬度且不为空的站点是运营中的
    operating_stations = stations_df.dropna(subset=coord_columns)
    
    # 如果有线路信息，也可以用来筛选
    line_columns = [col for col in stations_df.columns if '线路' in col or 'line' in col.lower()]
    if line_columns:
        line_col = line_columns[0]
        operating_stations = operating_stations.dropna(subset=[line_col])
    
    # 如果有年份信息，假设在当前年份或之前开通的站点为运营中
    if '年份' in stations_df.columns:
        current_year = datetime.datetime.now().year
        operating_stations = operating_stations[operating_stations['年份'] <= current_year]
    
    print(f"筛选出{len(operating_stations)}个可能运营中的站点")
    return operating_stations

def extract_city_data(stations_df, lines_df, flow_df, city_name="昆明"):
    """提取指定城市的站点和线路数据，仅包括运营中的站点"""
    # 提取站点数据
    city_stations = stations_df[stations_df['城市'] == city_name]
    print(f"{city_name}地铁站点总数量: {len(city_stations)}个")
    
    # 筛选出运营中的站点
    operating_stations = filter_operating_stations(city_stations)
    print(f"{city_name}运营中的地铁站点数量: {len(operating_stations)}个")
    
    # 提取线路数据
    city_lines = lines_df[lines_df['城市'] == city_name]
    print(f"{city_name}地铁线路数量: {len(city_lines)}条")
    
    # 提取客流量数据
    city_column = None
    
    # 先尝试精确格式的列名
    exact_pattern = [col for col in flow_df.columns if col == f"{city_name}:地铁客流量" or 
                    col == f"{city_name}：地铁客流量"]
    if exact_pattern:
        city_column = exact_pattern[0]
    else:
        # 再尝试模糊匹配
        pattern_columns = [col for col in flow_df.columns if f"{city_name}:" in col or 
                          f"{city_name}：" in col]
        if pattern_columns:
            city_column = pattern_columns[0]
        else:
            # 最后直接查找城市名作为列名
            if city_name in flow_df.columns:
                city_column = city_name
    
    if not city_column:
        print(f"未找到{city_name}的客流量数据")
        city_flow = None
    else:
        # 创建一个新的DataFrame包含日期和该城市的客流量
        city_flow = pd.DataFrame()
        
        # 检查是否有包含"日期"的列
        date_col = None
        for col in flow_df.columns:
            if '日期' in col or 'date' in col.lower() or '时间' in col:
                date_col = col
                break
        
        if date_col:
            # 如果有日期列，直接使用
            city_flow['日期'] = pd.to_datetime(flow_df[date_col], errors='coerce')
        else:
            # 否则使用指标名称列
            if '指标名称' in flow_df.columns:
                city_flow['日期'] = pd.to_datetime(flow_df['指标名称'].iloc[3:], errors='coerce')
            else:
                # 如果没有合适的日期列，使用第一列
                city_flow['日期'] = pd.to_datetime(flow_df.iloc[3:, 0], errors='coerce')
        
        # 转换客流量数据，将非数值数据转换为NaN
        if '指标名称' in flow_df.columns and len(flow_df) > 3:
            # 忽略前三行（单位行、来源行和表头行），从第四行开始
            city_flow['客流量'] = pd.to_numeric(flow_df[city_column].iloc[3:], errors='coerce')
        else:
            # 直接转换所有数据
            city_flow['客流量'] = pd.to_numeric(flow_df[city_column], errors='coerce')
        
        # 删除包含NaN的行
        city_flow = city_flow.dropna()
        
        # 添加日期相关特征
        city_flow['年份'] = city_flow['日期'].dt.year
        city_flow['月份'] = city_flow['日期'].dt.month
        city_flow['日'] = city_flow['日期'].dt.day
        city_flow['星期'] = city_flow['日期'].dt.dayofweek
        city_flow['是否周末'] = city_flow['星期'].apply(lambda x: 1 if x >= 5 else 0)
        
        print(f"提取{city_name}客流量数据: {len(city_flow)}条记录")
    
    return operating_stations, city_lines, city_flow

if __name__ == "__main__":
    # 该脚本作为模块被其他脚本调用，不单独运行
    pass 